package com.liuwei.learning.service;

import com.liuwei.learning.jpa.testdb1.Article;
import com.liuwei.learning.jpa.testdb1.ArticleRepository;
import com.liuwei.learning.jpa.testdb2.Message;
import com.liuwei.learning.jpa.testdb2.MessageRepository;
import com.liuwei.learning.model.ArticleVO;
import com.liuwei.learning.utils.DozerUtils;
import org.dozer.Mapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ArticleRestJPAServiceImpl implements  ArticleRestService  {

    //将JPA仓库对象注入
    @Resource
    private ArticleRepository articleRepository;

    @Resource
    private MessageRepository messageRepository;

    @Resource
    private Mapper dozerMapper;


    @Override
    @Transactional
    public ArticleVO saveArticle(ArticleVO article) {
        Article articlePO = dozerMapper.map(article,Article.class);
        articleRepository.save(articlePO);
        Message message = new Message();
        message.setName("t2222est message");
        message.setContent("text message content");
        messageRepository.save(message);
        int a = 2/0;
        return article;

    }


    @Override
    public void deleteArticle(Long id) {

    }

    @Override
    public void updateArticle(ArticleVO article) {

    }

    @Override
    public ArticleVO getArticle(Long id) {
        return null;
    }

    @Override
    public List<ArticleVO> getAll() {
        Pageable pageable = PageRequest.of(0,10, Sort.by("author").descending());
        Page<Article> articlePage = articleRepository.findAll(pageable);
        List<Article> articleList = articlePage.getContent();
        List<ArticleVO> articleVOS = DozerUtils.mapList(articleList,ArticleVO.class);
        return articleVOS;
    }
}